from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import sys

import os
from google.appengine.ext.webapp import template

from models import *
global pcategory
class MainPage(webapp.RequestHandler):
	global pcategory
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='user':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/admin")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global pcategory
		c=db.GqlQuery("SELECT * FROM projectCategory")
		pcategory=[]
		self.response.out.write(c)
		for i in c:
			tmp=[]
			tmp.append(i.categorytype.replace(" ","_"))
			tmp.append(i.categorytype)
			tmp.append(i.categoryid)
			tmp.append(i.maxprojects)
			pcategory.append(tmp)
		path = os.path.join(os.path.dirname(__file__),'cat.html')#use template
		self.response.out.write(template.render(path,{"category":pcategory}))#using template

	def post(self):
		global pcategory
		k=projectDetails()
		k.category=self.request.get("category")
		for i in pcategory:
			if i[0]==k.category:
				break
		k.category=i[2]
		user = users.get_current_user()
		if user:
			try:
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='%s'" %(user.email()))
				for i in userdet:
					if(i.projectids==None):
						break
					projunderme=i.projectids.split(",")
					for pid in projunderme:
						projdets=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %pid)
						for j in projdets:
							if j.category==k.category:
								path = os.path.join(os.path.dirname(__file__),'categoryerror.html')#use template
								self.response.out.write(template.render(path,{}))#using template
								return
				key=k.put()
				ids=key.id()
				k.projectid=str(ids)
				k.put()
				del pcategory[:]
				self.redirect("/notification?%s=id" %ids)
			except:
				pass

application=webapp.WSGIApplication([('/category',MainPage)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
